<?php
/*
* @Author: 李明
* @Date: 2021-08-18 13:36:21
 * @LastEditTime: 2022-01-22 11:23:04
 * @LastEditors: 李明
* @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/system/DataController.php
* @山东壹零贰肆信息科技有限公司
*/

namespace App\Http\Controllers\system;

use App\Http\Controllers\admin\BranchController;
use App\Http\Controllers\BranchUtils;
use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\HistoryDatum;
use App\Models\InterestRecord;
use App\Models\Order;
use App\Models\Worker;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Utils;

class DataController extends Controller
{
    /**
     * @description: 默认查询登录人员的直级部门业绩
     * @param {Request} $request
     * @return {*}
     */
    public function resultsBranchData(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::find($worker_id);
        $branch_list_base = BranchUtils::getAllBranchs();
        $branch_manage_list = $worker->branchesManage;
        $mbranch_id_list = [];
        if (count($branch_manage_list) == 0) {
            return LMReturn::Error('您没有管理该部门的权限', 'DCRBD1');
        } else {
            $mbranch_id_list = [];
            $child_list = [];
            foreach ($branch_manage_list as $b_m) {
                $mbranch_id_list[] = $b_m['id'];
                $a_child_list = $branch_list_base[$b_m['id']];
                if (count($a_child_list) > 0) {
                    foreach ($a_child_list as $a_child) {
                        $child_list[] = $a_child;
                    }
                }
                // $mbranch_id_list  = BranchUtils::getChildBranchs($b_m['id'], $branch_list_base, $mbranch_id_list);
            }
        }
        // 直系部门
        if (isset($all['manage_bm'])) {
            $manage_bm = $all['manage_bm'];
            $is_power = false;
            if (in_array($manage_bm, $mbranch_id_list)) {
                $is_power = true;
            }
            if (!$is_power) {
                return LMReturn::Error('您没有管理该部门的权限', 'DCRBD');
            } else {
                // $mbranch_id_list = BranchUtils::getChildBranchs($manage_bm, $branch_list_base, [$manage_bm]);
            }
            $child_list =  $branch_list_base[$manage_bm];
        }
        $resultData = [];
        $nowDay = date('Y-m-d', time());
        $nowYear = date('Y', time());
        $nowMonth = date('Y-m', time());
        $month_num = date('m', time());
        $week_start = date('Y-m-d', strtotime(Carbon::now()->startOfWeek()));
        $week_end = date('Y-m-d', strtotime(Carbon::now()->endOfWeek()));

        $upYear = date('Y', time()) - 1;
        $up_month_num = date('m', time()) - 1;
        $up_week_start = date('Y-m-d', strtotime(Carbon::now()->subWeek()->startOfWeek()));
        $up_week_end = date('Y-m-d', strtotime(Carbon::now()->subWeek()->endOfWeek()));
        $is_first = isset($all['is_first']) ? $all['is_first'] : 0;


        foreach ($child_list as $branch) {
            // $branch_id = $branch_id->id;
            $branchData['name'] = $branch['name'];
            $branchData['id'] = $branch['id'];
            $sum_branch_list_id = [];
            $sum_branch_list_id = BranchUtils::getChildBranchs($branch['id'], $branch_list_base, [$branch['id']]);
            $upYearData = $this->branch_data($sum_branch_list_id, $upYear . '-01-01', $upYear . '-12-31', $is_first, $worker_id);
            $yearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', $is_first, $worker_id);
            if ($month_num > 6) {
                $halfYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-07-01', $nowYear . '-12-31', $is_first, $worker_id);
            } else {
                $halfYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', $is_first, $worker_id);
            }
            $upMonthData = $this->branch_data($sum_branch_list_id, $nowYear . $up_month_num . '-01', $nowYear . $up_month_num . '-31', $is_first, $worker_id);
            $monthData = $this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', $is_first, $worker_id);
            $upWeekData = $this->branch_data($sum_branch_list_id, $up_week_start, $up_week_end, $is_first, $worker_id);
            $weekData = $this->branch_data($sum_branch_list_id, $week_start, $week_end, $is_first, $worker_id);
            $dayData = $this->branch_data($sum_branch_list_id, $nowDay, $nowDay, $is_first, $worker_id);

            $branchData['upYearMoneySize'] = round($upYearData['moneySize'], 2);
            $branchData['upYearMoneyRate'] = round($upYearData['moneyRate'], 2);

            $branchData['yearMoneySize'] = round($yearData['moneySize'], 2);
            $branchData['yearMoneyRate'] = round($yearData['moneyRate'], 2);

            $branchData['halfYearMoneySize'] = round($halfYearData['moneySize'], 2);
            $branchData['halfYearMoneyRate'] = round($halfYearData['moneyRate'], 2);

            $branchData['upMonthMoneySize'] = round($upMonthData['moneySize'], 2);
            $branchData['upMonthMoneyRate'] = round($upMonthData['moneyRate'], 2);

            $branchData['monthMoneySize'] = round($monthData['moneySize'], 2);
            $branchData['monthMoneyRate'] = round($monthData['moneyRate'], 2);

            $branchData['upWeekMoneySize'] = round($upWeekData['moneySize'], 2);
            $branchData['upWeekMoneyRate'] = round($upWeekData['moneyRate'], 2);

            $branchData['weekMoneySize'] = round($weekData['moneySize'], 2);
            $branchData['weekMoneyRate'] = round($weekData['moneyRate'], 2);

            $branchData['dayMoneySize'] = round($dayData['moneySize'], 2);
            $branchData['dayMoneyRate'] = round($dayData['moneyRate'], 2);
            $resultData[] = $branchData;
        }

        return LMReturn::Success($resultData);
    }

    /**
     * @description: 查询 登陆者管理的总部门的 年规模，年化   月规模，年化   日规模，年化
     * @param {Request} $request
     * @return {*}
     */
    public function resultsData(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::find($worker_id);
        $nowDay = date('Y-m-d', time());
        $nowYear = date('Y', time());
        $upYear = date('Y', time()) - 1;
        $nowMonth = date('Y-m', time());
        $month_num = date('m', time());
        $up_month_num = date('m', time()) - 1;
        $up_week_start = date('Y-m-d', strtotime(Carbon::now()->subWeek()->startOfWeek()));
        $up_week_end = date('Y-m-d', strtotime(Carbon::now()->subWeek()->endOfWeek()));
        $week_start = date('Y-m-d', strtotime(Carbon::now()->startOfWeek()));
        $week_end = date('Y-m-d', strtotime(Carbon::now()->endOfWeek()));
        $is_first = isset($all['is_first']) ? $all['is_first'] : 0;
        $sum_branch_list_id = Utils::getWorkerChildSonBranchs($worker);
        $upYearData = $this->branch_data($sum_branch_list_id, $upYear . '-01-01', $upYear . '-12-31', $is_first, $worker_id);
        $yearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', $is_first, $worker_id);
        if ($month_num > 6) {
            $halfYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-07-01', $nowYear . '-12-31', $is_first, $worker_id);
        } else {
            $halfYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', $is_first, $worker_id);
        }
        $upMonthData = $this->branch_data($sum_branch_list_id, $nowYear . $up_month_num . '-01', $nowYear . $up_month_num . '-31', $is_first, $worker_id);
        $monthData = $this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', $is_first, $worker_id);
        $upWeekData = $this->branch_data($sum_branch_list_id, $up_week_start, $up_week_end, $is_first, $worker_id);
        $weekData = $this->branch_data($sum_branch_list_id, $week_start, $week_end, $is_first, $worker_id);
        $dayData = $this->branch_data($sum_branch_list_id, $nowDay, $nowDay, $is_first, $worker_id);
        $resultData['upYearData'] = $upYearData;
        $resultData['yearData'] = $yearData;
        $resultData['halfYearData'] = $halfYearData;
        $resultData['upMonthData'] = $upMonthData;
        $resultData['monthData'] = $monthData;
        $resultData['upWeekData'] = $upWeekData;
        $resultData['weekData'] = $weekData;
        $resultData['dayData'] = $dayData;
        return LMReturn::Success($resultData);
    }

    /**
     * @description: 查询部门的年化和规模
     * @param {*} $branch_id 要查询的部门id
     * @param {*} $start_time 开始时间
     * @param {*} $end_time 结束时间
     * @return {*}
     */
    public function branch_data($branch_list_id, $start_time, $end_time, $type = 0, $worker_id = '0')
    {
        $where = [];
        // 开始时间
        $where[] = ["order.sign_time", ">=", $start_time];
        // 结束时间
        $where[] = ["order.sign_time", "<=", $end_time];
        $whereinOrder = [3, 4, 6];
        $sum_data = Order::where($where)
            ->whereIn('order.order_status', $whereinOrder)
            ->when(count($branch_list_id) > 0, function ($query) use ($branch_list_id) {
                return $query->whereIn('order.branch_id', $branch_list_id);
            })
            ->when(count($branch_list_id) == 0, function ($query) use ($worker_id) {
                return $query->where('order.worker_id', $worker_id);
            })
            ->when($type > 0, function ($query) use ($type) {
                return $query->where('is_first', $type);
            })
            ->first(
                array(
                    DB::raw('SUM(results_money) as moneyRate'),
                    DB::raw('SUM(order_money) as moneySize')
                )
            )->toArray();
        $sum_data['moneyRate'] = round($sum_data['moneyRate'], 2);
        $sum_data['moneySize'] = round($sum_data['moneySize'], 2);
        return $sum_data;
    }

    /**
     * @description: 修改产品年化比例之后更新数据使用
     * @param {Request} $request
     * @return {*}
     */
    public function updateOrderList(Request $request)
    {
        $orderList = json_decode(json_encode(
            Order::select(
                "order.id as order_id",
                "order.order_money",
                "product.results_rate",
            )
                ->leftjoin("product", "order.product_id", "=", "product.id")
                ->get()
        ), true);
        foreach ($orderList as $key => $order) {
            $updateData['results_rate'] = $order['results_rate'];
            $updateData['results_money'] = $order['results_rate'] * $order['order_money'] / 100.0;
            Order::where("id", $order['order_id'])
                ->update([
                    'results_money' => $updateData['results_money']
                ]);
        }
    }

    public function update_current_data(Request $request)
    {

        // $branch_list = Branch::all();

        // $nowDay = date('Y-m-d', time());
        // $nowYear = date('Y', time());
        // $nowMonth = date('Y-m', time());
        // $week_start = date('Y-m-d', strtotime(Carbon::now()->startOfWeek()));
        // $week_end = date('Y-m-d', strtotime(Carbon::now()->endOfWeek()));
        // $is_first = $all['is_first'] ?? 0;
        // foreach ($branch_list as $branch) {
        //     $time = Carbon::now();
        //     $dayOfWeek = $time->dayOfWeek;   //获取当前时间是这周的第几天
        //     $dayOfYear = $time->dayOfYear;   //获取当前时间是今年的第几天
        //     $weekOfYear = $time->weekOfYear;   //获取当前时间所以在周是当前年的第几周

        //     $data = new HistoryDatum();
        //     $data->branch_id = $branch->id;
        //     $data->month_day = $time->daysInMonth;   //获取当月是多少天
        //     $data->year = $time->year;
        //     $data->month = $time->month;   //获取当前的月
        //     $data->day = $time->day;   //获取当前的日
        //     $data->week = $weekOfYear;
        //     $data->day_of_year = $dayOfYear;

        //     // $branch_id = $branch_id->id;
        //     $branchData['name'] = $branch->name;
        //     $branchData['id'] = $branch->id;
        //     $is_all = true; // 默认查 所有的 子级部门的业绩。后期修改这里可以查其他的。
        //     if ($is_all) { // 默认所有
        //         $sum_branch_list = BranchController::get_branch_list($branch);
        //     } else { // 否则只查询本部门
        //         $sum_branch_list = [$branch];
        //     }
        //     $sum_branch_list_id = [];
        //     foreach ($sum_branch_list as $sum_branch) {
        //         $sum_branch_list_id[] = $sum_branch->id;
        //     }
        //     $yearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', $is_first, $worker_id);
        //     $halfTopYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-07-01', $nowYear . '-12-31', $is_first, $worker_id);
        //     $halfBottomYearData = $this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', $is_first, $worker_id);
        //     $monthData = $this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', $is_first, $worker_id);
        //     $weekData = $this->branch_data($sum_branch_list_id, $week_start, $week_end, $is_first, $worker_id);
        //     $dayData = $this->branch_data($sum_branch_list_id, $nowDay, $nowDay, $is_first, $worker_id);
        //     // 年
        //     $data->year_size = round($yearData['moneySize'], 2);
        //     $data->year_rate = round($yearData['moneyRate'], 2);
        //     $data->year_new_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 1)['moneySize'], 2);
        //     $data->year_new_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 1)['moneyRate'], 2);
        //     $data->year_stock_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 2)['moneySize'], 2);
        //     $data->year_stock_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 2)['moneyRate'], 2);
        //     $data->year_turn_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 3)['moneySize'], 2);
        //     $data->year_turn_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-12-31', 3)['moneyRate'], 2);
        //     // 上半年
        //     $data->top_half_year_size = round($halfTopYearData['moneySize'], 2);
        //     $data->top_half_year_rate = round($halfTopYearData['moneyRate'], 2);
        //     $data->top_half_year_new_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 1)['moneySize'], 2);
        //     $data->top_half_year_new_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 1)['moneyRate'], 2);
        //     $data->top_half_year_stock_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 2)['moneySize'], 2);
        //     $data->top_half_year_stock_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 2)['moneyRate'], 2);
        //     $data->top_half_year_turn_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 3)['moneySize'], 2);
        //     $data->top_half_year_turn_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-01-01', $nowYear . '-07-31', 3)['moneyRate'], 2);

        //     // 下半年
        //     $data->bottom_half_year_size = round($halfBottomYearData['moneySize'], 2);
        //     $data->bottom_half_year_rate = round($halfBottomYearData['moneyRate'], 2);
        //     $data->bottom_half_year_new_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 1)['moneySize'], 2);
        //     $data->bottom_half_year_new_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 1)['moneyRate'], 2);
        //     $data->bottom_half_year_stock_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 2)['moneySize'], 2);
        //     $data->bottom_half_year_stock_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 2)['moneyRate'], 2);
        //     $data->bottom_half_year_turn_size = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 3)['moneySize'], 2);
        //     $data->bottom_half_year_turn_rate = round($this->branch_data($sum_branch_list_id, $nowYear . '-07-31', $nowYear . '-12-31', 3)['moneyRate'], 2);
        //     // 月
        //     $data->month_size = round($monthData['moneySize'], 2);
        //     $data->month_rate = round($monthData['moneyRate'], 2);
        //     $data->month_new_size = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 1)['moneySize'], 2);
        //     $data->month_new_rate = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 1)['moneyRate'], 2);
        //     $data->month_stock_size = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 2)['moneySize'], 2);
        //     $data->month_stock_rate = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 2)['moneyRate'], 2);
        //     $data->month_turn_size = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 3)['moneySize'], 2);
        //     $data->month_turn_rate = round($this->branch_data($sum_branch_list_id, $nowMonth . '-01', $nowMonth . '-31', 3)['moneyRate'], 2);
        //     // 周
        //     $data->week_size = round($weekData['moneySize'], 2);
        //     $data->week_rate = round($weekData['moneyRate'], 2);
        //     $data->week_new_size = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 1)['moneySize'], 2);
        //     $data->week_new_rate = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 1)['moneyRate'], 2);
        //     $data->week_stock_size = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 2)['moneySize'], 2);
        //     $data->week_stock_rate = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 2)['moneyRate'], 2);
        //     $data->week_turn_size = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 3)['moneySize'], 2);
        //     $data->week_turn_rate = round($this->branch_data($sum_branch_list_id, $week_start, $week_end, 3)['moneyRate'], 2);
        //     // 日
        //     $data->day_size = round($dayData['moneySize'], 2);
        //     $data->day_rate = round($dayData['moneyRate'], 2);
        //     $data->day_new_size = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 1)['moneySize'], 2);
        //     $data->day_new_rate = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 1)['moneyRate'], 2);
        //     $data->day_stock_size = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 2)['moneySize'], 2);
        //     $data->day_stock_rate = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 2)['moneyRate'], 2);
        //     $data->day_turn_size = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 3)['moneySize'], 2);
        //     $data->day_turn_rate = round($this->branch_data($sum_branch_list_id, $nowDay, $nowDay, 3)['moneyRate'], 2);
        //     $data->save();
        // }
    }

    // 数据统计接口
    public function data_statistics(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $workers = Worker::where('id', $worker_id)->with('branchesManage')->first();
        if (count($workers['branchesManage']) > 0) {
            $worker_manage_branch = $workers['branchesManage'][0]['id'];
        } else {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        $branch_l[] = $worker_manage_branch;
        $branch_lists = Utils::getChildBranchs($worker_manage_branch, $branch_l);
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch;
        if (!(in_array($branch_id, $branch_lists))) {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        $branchs = Branch::find($branch_id);
        if (empty($branchs)) {
            return LMReturn::selectErr('没有该部门');
        }
        $all_data = [];
        $time = Carbon::now();
        $dayOfWeek = $time->dayOfWeek;   //获取当前时间是这周的第几天
        $dayOfYear = $time->dayOfYear;   //获取当前时间是今年的第几天
        $nowDay = date('d', time());    // 今天是几号

        $yesterday = Carbon::yesterday();       // 昨天
        $yesterweekend = Carbon::now()->subDays($dayOfWeek); //上周;
        $yestermonthend = Carbon::now()->subDays((int)$nowDay);                                          // 上个月1
        $beforelastmonth = Carbon::now()->subMonths(1)->modify('-' . (int)$nowDay . ' days');    // 上上个月2
        $before3lastmonth = Carbon::now()->subMonths(2)->modify('-' . (int)$nowDay . ' days');   // 上上上个月3
        $before4lastmonth = Carbon::now()->subMonths(3)->modify('-' . (int)$nowDay . ' days');   // 上上上上个月4
        $before5lastmonth = Carbon::now()->subMonths(4)->modify('-' . (int)$nowDay . ' days');   // 上上上上上个月5
        $before6lastmonth = Carbon::now()->subMonths(5)->modify('-' . (int)$nowDay . ' days');   // 上上上上上上个月6
        $before7lastmonth = Carbon::now()->subMonths(6)->modify('-' . (int)$nowDay . ' days');   // 上上上上上上上个月7
        $before8lastmonth = Carbon::now()->subMonths(7)->modify('-' . (int)$nowDay . ' days');   // 上上上上上上上上个月8
        $before9lastmonth = Carbon::now()->subMonths(8)->modify('-' . (int)$nowDay . ' days');   // 上上上上上上上上上个月9
        $before10lastmonth = Carbon::now()->subMonths(9)->modify('-' . (int)$nowDay . ' days');  // 上上上上上上上上上上个月10
        $before11lastmonth = Carbon::now()->subMonths(10)->modify('-' . (int)$nowDay . ' days'); // 上上上上上上上上上上上个月11

        $yesteryearend = Carbon::now()->subDays($dayOfYear); //去年;2020
        $beforelastyear = Carbon::now()->subDays(($dayOfYear + $yesteryearend->daysInYear)); //前年;2019

        // 昨天数据
        $yesterday_data = $this->get_datas($branch_id, strtotime($yesterday));
        // 上周数据
        $yesterweek_data = $this->get_datas($branch_id, strtotime($yesterweekend));
        // 上个月数据
        $yestermonth_data = $this->get_datas($branch_id, strtotime($yestermonthend));
        // 去年数据
        $yesteryear_data = $this->get_datas($branch_id, strtotime($yesteryearend));
        // 前年数据
        $beforelastyear_data = $this->get_datas($branch_id, strtotime($beforelastyear));
        // 上上个月数据
        $beforelastmonth_data = $this->get_datas($branch_id, strtotime($beforelastmonth));
        // 上上上个月数据
        $before3lastmonth_data = $this->get_datas($branch_id, strtotime($before3lastmonth));
        // 上上上上个月数据
        $before4lastmonth_data = $this->get_datas($branch_id, strtotime($before4lastmonth));
        // 上上上上上个月数据
        $before5lastmonth_data = $this->get_datas($branch_id, strtotime($before5lastmonth));
        // 上上上上上上个月数据
        $before6lastmonth_data = $this->get_datas($branch_id, strtotime($before6lastmonth));
        // 上上上上上上上个月数据
        $before7lastmonth_data = $this->get_datas($branch_id, strtotime($before7lastmonth));
        // 上上上上上上上上个月数据
        $before8lastmonth_data = $this->get_datas($branch_id, strtotime($before8lastmonth));
        // 上上上上上上上上上个月数据
        $before9lastmonth_data = $this->get_datas($branch_id, strtotime($before9lastmonth));
        // 上上上上上上上上上上个月数据
        $before10lastmonth_data = $this->get_datas($branch_id, strtotime($before10lastmonth));
        // 上上上上上上上上上上上个月数据
        $before11lastmonth_data = $this->get_datas($branch_id, strtotime($before11lastmonth));

        // 业绩统计
        $performance_statistics = [];
        $performance_statistics_size = [];
        $performance_statistics_rate = [];

        // 业绩分析
        $size_list = ['规模'];
        $rate_list = ['年化'];
        $out_gold = ['出金'];
        // 业务存量
        $business_stock = [];
        // 上个周
        if (isset($yesterweek_data)) {
            $performance_statistics_size['yesterweek_year'] = $yesterweek_data->year_size;
            $performance_statistics_rate['yesterweek_year'] = round($yesterweek_data->year_rate, 2);
        } else {
            $performance_statistics_size['yesterweek_year'] = 0.00;
            $performance_statistics_rate['yesterweek_year'] = 0.00;
        }
        // 去年
        if (isset($yesteryear_data)) {
            $performance_statistics_size['yesteryear_year'] = $yesteryear_data->year_size;
            $performance_statistics_rate['yesteryear_year'] = round($yesteryear_data->year_rate, 2);
        } else {
            $performance_statistics_size['yesteryear_year_size'] = 0.00;
            $performance_statistics_rate['yesteryear_year_rate'] = 0.00;
        }
        // 前年
        if (isset($beforelastyear_data)) {
            $performance_statistics_size['beforelastyear_year'] = $beforelastyear_data->year_size;
            $performance_statistics_rate['beforelastyear_year'] = round($beforelastyear_data->year_rate, 2);
        } else {
            $performance_statistics_size['beforelastyear_year'] = 0.00;
            $performance_statistics_rate['beforelastyear_year'] = 0.00;
        }
        // 昨天
        if (isset($yesterday_data)) {
            $performance_statistics_size['week'] = $yesterday_data->week_size;
            $performance_statistics_rate['week'] = round($yesterday_data->week_rate, 2);
            $performance_statistics_size['month'] = $yesterday_data->month_size;
            $performance_statistics_rate['month'] = round($yesterday_data->month_rate, 2);
            $performance_statistics_size['year'] = $yesterday_data->year_size;
            $performance_statistics_rate['year'] = round($yesterday_data->year_rate, 2);
            $performance_statistics_size['half'] = (int)($yesterday_data->top_half_year_size) == 0 ? $yesterday_data->bottom_half_year_size : $yesterday_data->top_half_year_size;
            $performance_statistics_rate['half'] = (int)($yesterday_data->top_half_year_rate) == 0 ? round($yesterday_data->bottom_half_year_rate, 2) : round($yesterday_data->top_half_year_rate, 2);
            $size_list[] = $yesterday_data->month_size;
            $rate_list[] = round($yesterday_data->month_rate, 2);
            $out_gold[] = $yesterday_data->month_out_glod ?? 0.00;
            $business_stock['history_all_count'] = $yesterday_data->all_count;
            $business_stock['now_existing'] = $yesterday_data->existing;
        } else {
            $performance_statistics_size['week'] = 0.00;
            $performance_statistics_rate['week'] = 0.00;
            $performance_statistics_size['month'] = 0.00;
            $performance_statistics_rate['month'] = 0.00;
            $performance_statistics_size['year'] = 0.00;
            $performance_statistics_rate['year'] = 0.00;
            $performance_statistics_size['half'] = 0.00;
            $performance_statistics_rate['half'] = 0.00;
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
            $business_stock['history_all_count'] = 0.00;
            $business_stock['now_existing'] = 0.00;
        }
        // 上个月
        if (isset($yestermonth_data)) {
            $performance_statistics_size['yestermonth_year'] = $yestermonth_data->year_size;
            $performance_statistics_rate['yestermonth_year'] = round($yestermonth_data->year_rate, 2);
            $size_list[] = $yestermonth_data->month_size;
            $rate_list[] = round($yestermonth_data->month_rate, 2);
            $out_gold[] = $yestermonth_data->month_out_glod ?? 0.00;
        } else {
            $performance_statistics_size['yestermonth_year'] = 0.00;
            $performance_statistics_rate['yestermonth_year'] = 0.00;
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上个月数据
        if (isset($beforelastmonth_data)) {
            $size_list[] = $beforelastmonth_data->month_size;
            $rate_list[] = round($beforelastmonth_data->month_rate, 2);
            $out_gold[] = $beforelastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上个月数据
        if (isset($before3lastmonth_data)) {
            $size_list[] = $before3lastmonth_data->month_size;
            $rate_list[] = round($before3lastmonth_data->month_rate, 2);
            $out_gold[] = $before3lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上个月数据
        if (isset($before4lastmonth_data)) {
            $size_list[] = $before4lastmonth_data->month_size;
            $rate_list[] = round($before4lastmonth_data->month_rate, 2);
            $out_gold[] = $before4lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上个月数据
        if (isset($before5lastmonth_data)) {
            $size_list[] = $before5lastmonth_data->month_size;
            $rate_list[] = round($before5lastmonth_data->month_rate, 2);
            $out_gold[] = $before5lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上个月数据
        if (isset($before6lastmonth_data)) {
            $size_list[] = $before6lastmonth_data->month_size;
            $rate_list[] = round($before6lastmonth_data->month_rate, 2);
            $out_gold[] = $before6lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上上个月数据
        if (isset($before7lastmonth_data)) {
            $size_list[] = $before7lastmonth_data->month_size;
            $rate_list[] = round($before7lastmonth_data->month_rate, 2);
            $out_gold[] = $before7lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上上上个月数据
        if (isset($before8lastmonth_data)) {
            $size_list[] = $before8lastmonth_data->month_size;
            $rate_list[] = round($before8lastmonth_data->month_rate, 2);
            $out_gold[] = $before8lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上上上上个月数据
        if (isset($before9lastmonth_data)) {
            $size_list[] = $before9lastmonth_data->month_size;
            $rate_list[] = round($before9lastmonth_data->month_rate, 2);
            $out_gold[] = $before9lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上上上上上个月数据
        if (isset($before10lastmonth_data)) {
            $size_list[] = $before10lastmonth_data->month_size;
            $rate_list[] = round($before10lastmonth_data->month_rate, 2);
            $out_gold[] = $before10lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 上上上上上上上上上上上个月数据
        if (isset($before11lastmonth_data)) {
            $size_list[] = $before11lastmonth_data->month_size;
            $rate_list[] = round($before11lastmonth_data->month_rate, 2);
            $out_gold[] = $before11lastmonth_data->month_out_glod ?? 0.00;
        } else {
            $size_list[] = 0.00;
            $rate_list[] = 0.00;
            $out_gold[] = 0.00;
        }
        // 出金预估
        $all_data['gold_forecast'] = $this->gold_forecast($branch_id);
        // 业绩统计
        $performance_statistics[] = $performance_statistics_size;
        $performance_statistics[] = $performance_statistics_rate;
        $all_data['performance_statistics'] = $performance_statistics;

        // 业绩分析
        $all_data['performance_analysis'] = [$size_list, $rate_list, $out_gold];

        // 业务存量
        $all_data['business_stock'] = $business_stock;

        return LMReturn::Success($all_data);
    }

    public function get_datas($branch_id, $date)
    {
        $year = date('Y', $date);
        $month = (int)date('m', $date);
        $day = (int)date('d', $date);
        return HistoryDatum::where('branch_id', $branch_id)
            ->where('year', $year)
            ->where('month', $month)
            ->where('day', $day)->first();
    }

    public function getOtherDatas(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $workers = Worker::where('id', $worker_id)->with('branchesManage')->first();
        if (count($workers['branchesManage']) > 0) {
            $worker_manage_branch = $workers['branchesManage'][0]['id'];
        } else {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        $branch_l[] = $worker_manage_branch;
        $branch_lists = Utils::getChildBranchs($worker_manage_branch, $branch_l);
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch;
        if (!(in_array($branch_id, $branch_lists))) {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        if (empty($all['start_time']) || empty($all['end_time'])) {
            return LMReturn::selectErr('未传入起始时间或结束时间');
        }
        $branchs = Branch::find($branch_id);
        if (empty($branchs)) {
            return LMReturn::selectErr('没有该部门');
        }
        if (($all['end_time'] / 1000 - 1) > time()) {
            $end_time = strtotime(Carbon::yesterday());
        } else {
            $end_time = ($all['end_time']) / 1000 - 1;
        }
        $start_end_times = ($all['end_time'] - $all['start_time']) / 1000;
        $all_data = [];
        // 业绩占比
        $branch_list = Branch::where('pid', $branch_id)->get();
        $week_data = [];
        $month_data = [];
        $year_data = [];
        if (isset($branch_list)) {
            foreach ($branch_list as $branch) {
                $child_yesterday_data = $this->get_datas($branch['id'], $end_time);
                if (isset($child_yesterday_data)) {
                    $week_data[] = [$branch->name, $child_yesterday_data->week_size];
                    $month_data[] = [$branch->name, $child_yesterday_data->month_size];
                    $year_data[] = [$branch->name, $child_yesterday_data->year_size];
                } else {
                    $week_data[] = [$branch->name, 0.00];
                    $month_data[] = [$branch->name, 0.00];
                    $year_data[] = [$branch->name, 0.00];
                }
            }
        }
        if ($start_end_times <= 604800) {
            $all_data['branch_size_list'] = $week_data;
        } elseif ($start_end_times >= 1209600 && $start_end_times <= 2764800) {
            $all_data['branch_size_list'] = $month_data;
        } else {
            $all_data['branch_size_list'] = $year_data;
        }
        // 客户分析
        if ($start_end_times <= 604800) {        // 周
            $all_data['costumor'] = $this->getCustermorData($branch_id, $end_time, 1);
        } elseif ($start_end_times >= 1209600 && $start_end_times <= 2764800) {
            $all_data['costumor'] = $this->getCustermorData($branch_id, $end_time, 2);        // 月
        } else {            // 年
            $all_data['costumor'] = $this->getCustermorData($branch_id, $end_time, 3);
        }
        return LMReturn::Success($all_data);
    }

    public function getCustermorData($branch_id, $end_time, $type)
    {
        $year = date('Y', $end_time);
        $month = (int)date('m', $end_time);
        if (time() - $end_time < 86400) {
            $day = (int)date('d', $end_time - 86400);
        } else {
            $day = (int)date('d', $end_time);
        }
        $datas = HistoryDatum::where('branch_id', $branch_id)
            ->where('year', $year)
            ->where('month', $month)
            ->where('day', $day)->first();
        $new_list[] = '新单客户';
        $stock_list[] = '存量客户';
        $turn_list[] = '转续客户';
        if ($type == 1) {
            $new_list[] = $datas->week_new_count ?? 0;
            $new_list[] = $datas->week_new_size ?? 0;
            $new_list[] = $datas->week_new_rate ?? 0;
            $stock_list[] = $datas->week_stock_count ?? 0;
            $stock_list[] = $datas->week_stock_size ?? 0;
            $stock_list[] = $datas->week_stock_rate ?? 0;
            $turn_list[] = $datas->week_turn_count ?? 0;
            $turn_list[] = $datas->week_turn_size ?? 0;
            $turn_list[] = $datas->week_turn_rate ?? 0;
        } elseif ($type == 2) {
            $new_list[] = $datas->month_new_count ?? 0;
            $new_list[] = $datas->month_new_size ?? 0;
            $new_list[] = $datas->month_new_rate ?? 0;
            $stock_list[] = $datas->month_stock_count ?? 0;
            $stock_list[] = $datas->month_stock_size ?? 0;
            $stock_list[] = $datas->month_stock_rate ?? 0;
            $turn_list[] = $datas->month_turn_count ?? 0;
            $turn_list[] = $datas->month_turn_size ?? 0;
            $turn_list[] = $datas->month_turn_rate ?? 0;
        } else {
            $new_list[] = $datas->year_new_count ?? 0;
            $new_list[] = $datas->year_new_size ?? 0;
            $new_list[] = $datas->year_new_rate ?? 0;
            $stock_list[] = $datas->year_stock_count ?? 0;
            $stock_list[] = $datas->year_stock_size ?? 0;
            $stock_list[] = $datas->year_stock_rate ?? 0;
            $turn_list[] = $datas->year_turn_count ?? 0;
            $turn_list[] = $datas->year_turn_size ?? 0;
            $turn_list[] = $datas->year_turn_rate ?? 0;
        }
        return [$new_list, $stock_list, $turn_list];
    }
    /**
     * @description:
     * @param {*} $branch_id  部门id
     * @return array 从现在到12个月之后的出金金额
     */
    public function gold_forecast($branch_id)
    {
        $data_list = [];
        for ($i = 0; $i < 12; $i++) {
            $month_start = date(Carbon::now()->addMonths($i)->startOfMonth());
            $month_end = date(Carbon::now()->addMonths($i)->endOfMonth());
            $interest_recodes = InterestRecord::where('date', '>=', $month_start)
                ->where('date', '<=', $month_end)
                ->when($branch_id != 3, function ($query) use ($branch_id) {
                    return $query->where('branch_id', $branch_id);
                })
                ->get();
            $interest_money = 0;
            foreach ($interest_recodes as $interest) {
                $interest_money = $interest->payment_amount;
            }
            $data_list[] = $interest_money;
        }
        return $data_list;
    }
    /**
     * @description:
     * @param {*} $branch_id 要查询的部门
     * @param {*} $num 查询多少个月内的，默认12
     * @return array
     */
    public function results_month($branch_id, $num = 12)
    {
        $data_list = [];
        $num = $num - 1;
        for ($i = $num; $i >= 0; $i--) {
            $month_start = date(Carbon::now()->subMonths($i)->startOfMonth());
            $month_end = date(Carbon::now()->subMonths($i)->endOfMonth());
            $interest_recodes = InterestRecord::where('date', '>=', $month_start)
                ->where('date', '<=', $month_end)
                ->when($branch_id != 3, function ($query) use ($branch_id) {
                    return $query->where('branch_id', $branch_id);
                })
                ->get();
            $interest_money = 0;
            foreach ($interest_recodes as $interest) {
                $interest_money = $interest->payment_amount;
            }
            $data_list[] = $interest_money;
        }
        return $data_list;
    }

    public function financialReconcliation(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $workers = Worker::where('id', $worker_id)->with('branchesManage')->first();
        if (count($workers['branchesManage']) > 0) {
            $worker_manage_branch = $workers['branchesManage'][0]['id'];
        } else {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        $branch_l[] = $worker_manage_branch;
        $branch_lists = Utils::getChildBranchs($worker_manage_branch, $branch_l);
        $all = $request->all();
        $branch_id = $all['branch_id'] ?? $worker_manage_branch;
        if (!(in_array($branch_id, $branch_lists))) {
            return LMReturn::Error('抱歉！您没有权限查看');
        }
        if (empty($all['start_time']) || empty($all['end_time'])) {
            return LMReturn::selectErr('未传入起始时间或结束时间');
        }
        $branchs = Branch::find($branch_id);
        if (empty($branchs)) {
            return LMReturn::selectErr('没有该部门');
        }
        if (($all['end_time'] / 1000) - 1 > time()) {
            $end_time = strtotime(Carbon::yesterday());
        } else {
            $end_time = ($all['end_time']) / 1000 - 1;
        }
        $start_end_times = ($all['end_time'] - $all['start_time']) / 1000;
        $yesterday_data = $this->get_datas($branch_id, $end_time);
        if (isset($yesterday_data)) {
            if ($start_end_times <= 604800) {        // 周
                $week_financial['in_gold'] = $yesterday_data->week_size;
                $week_financial['out_gold'] = $yesterday_data->week_out_gold;
                $week_financial['net_into_gold'] = $yesterday_data->week_size - $yesterday_data->week_out_gold;
                $week_financial['poundage'] = round($yesterday_data->week_poundage, 2);
                $week_financial['oa_fanince'] = $yesterday_data->week_oa_fanince;
                $week_financial['real_golden'] = $yesterday_data->week_size - $yesterday_data->week_out_gold - $yesterday_data->week_poundage - $yesterday_data->week_oa_fanince;
                return LMReturn::Success($week_financial);
            } elseif ($start_end_times >= 1209600 && $start_end_times <= 2764800) {
                $month_financial['in_gold'] = $yesterday_data->month_size;
                $month_financial['out_gold'] = $yesterday_data->month_out_gold;
                $month_financial['net_into_gold'] = $yesterday_data->month_size - $yesterday_data->month_out_gold;
                $month_financial['poundage'] = round($yesterday_data->month_poundage, 2);
                $month_financial['oa_fanince'] = $yesterday_data->month_oa_fanince;
                $month_financial['real_golden'] = $yesterday_data->month_size - $yesterday_data->month_out_gold - $yesterday_data->month_poundage - $yesterday_data->month_oa_fanince;
                return LMReturn::Success($month_financial);
            } else {            // 年
                $year_financial['in_gold'] = $yesterday_data->year_size;
                $year_financial['out_gold'] = $yesterday_data->year_out_gold;
                $year_financial['net_into_gold'] = $yesterday_data->year_size - $yesterday_data->year_out_gold;
                $year_financial['poundage'] = round($yesterday_data->year_poundage, 2);
                $year_financial['oa_fanince'] = $yesterday_data->year_oa_fanince;
                $year_financial['real_golden'] = $yesterday_data->year_size - $yesterday_data->year_out_gold - $yesterday_data->year_poundage - $yesterday_data->year_oa_fanince;
                return LMReturn::Success($year_financial);
            }
        } else {
            $datas['in_gold'] = 0;
            $datas['out_gold'] = 0;
            $datas['net_into_gold'] = 0;
            $datas['poundage'] = 0;
            $datas['oa_fanince'] = 0;
            $datas['real_golden'] = 0;
            return LMReturn::Success($datas);
        }
    }
}
